package com.platform.common.annotation;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.platform.common.util.DateUtils;

/**
 * 切点类
 */
@Aspect
@Component
public class SystemLogAspect {

	// 本地异常日志记录对象
	private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);

	// Controller层切点
	@Pointcut("@annotation(com.netbox.service.common.annotation.SystemControllerLog)")
	public void controllerAspect() {
	}

	/**
	 * 前置通知 用于拦截Controller层记录用户的操作
	 * 
	 * @param joinPoint
	 *            切点
	 */
	@Before("controllerAspect()")
	public void doBefore(JoinPoint joinPoint) {

		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		HttpSession session = request.getSession();

		// 读取session中的用户
		// User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
		// 请求的IP
		String logIP = request.getHeader("X-Real-IP");
		if (StringUtils.isEmpty(logIP)) {
			logIP = request.getRemoteAddr();
		}
		try {
			SystemLogModel slm = getControllerMethodDescription(joinPoint);
			slm.setLogIP(logIP);
			slm.setTimeFlag(DateUtils.currentDatetime());
			if (null == request.getParameter("UserID") || null == request.getParameter("UserName")) {
				logger.debug("操作日志-->日志添加:用户名或用户ID为空，返回不添加日志!");
				return;
			}

			slm.setFlagID(Integer.parseInt(request.getParameter("UserID").toString()));
			slm.setFlagName(request.getParameter("UserName").toString());

			// *========控制台输出=========*//
			logger.debug("=====注解参数获取开始=====");
			logger.debug("请求方法:"
					+ (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
			logger.debug("操作模块:" + slm.getModuleID());
			logger.debug("操作方法:" + slm.getLogAction());
			logger.debug("操作内容:" + slm.getLogContent());
			logger.debug("请求IP:" + slm.getLogIP());
			logger.debug("FlagID:" + slm.getFlagID());
			logger.debug("FlagName:" + slm.getFlagName());
			// *========数据库日志=========*//
			String sql = "insert into [WFBDCMain].[dbo].[ISIP_log_Operation]([FlagID],[FlagName],[LogAction],[LogContent],[LogIP] ,[ModuleID],[TimeFlag])"
					+ " values("
					+ slm.getFlagID()
					+ ",'"
					+ slm.getFlagName()
					+ "','"
					+ slm.getLogAction()
					+ "','"
					+ slm.getLogContent()
					+ "','"
					+ slm.getLogIP()
					+ "',"
					+ slm.getModuleID()
					+ ",'"
					+ slm.getTimeFlag() + "')";
			// jdbcTemplate.update(sql);

		} catch (Exception e) {
			// 记录本地异常日志
			logger.error("==前置通知异常==");
			logger.error("异常信息:{}", e.getMessage());
		}
	}

	/**
	 * 获取注解中对方法的描述信息 用于Controller层注解
	 * 
	 * @param joinPoint
	 *            切点
	 * @return 方法描述
	 * @throws Exception
	 */
	public static SystemLogModel getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
		String targetName = joinPoint.getTarget().getClass().getName();
		String methodName = joinPoint.getSignature().getName();
		Object[] arguments = joinPoint.getArgs();
		Class targetClass = Class.forName(targetName);
		Method[] methods = targetClass.getMethods();
		String description = "";
		SystemControllerLog log;
		SystemLogModel logM = new SystemLogModel();
		for (Method method : methods) {
			if (method.getName().equals(methodName)) {
				Class[] clazzs = method.getParameterTypes();
				if (clazzs.length == arguments.length) {
					log = method.getAnnotation(SystemControllerLog.class);
					logM.setModuleID(log.ModuleID());
					logM.setLogAction(log.LogAction());
					logM.setLogContent(log.LogContent());
					break;
				}
			}
		}
		return logM;
	}
}